package com.demo.idempotent.compotent;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock {
    public static ThreadLocal<RedisTemplate> holder = new ThreadLocal<>();

    private String lockKey;
    private long ttl = 5;


    public SimpleRedisLock(RedisTemplate redisTemplate, String key) {
        holder.set(redisTemplate);
        this.lockKey = key;
    }

    public SimpleRedisLock(RedisTemplate redisTemplate, String key, long ttl) {
        holder.set(redisTemplate);
        this.lockKey = key;
        this.ttl = ttl;
    }

    public Boolean acquire() {
        return holder.get().opsForValue().setIfAbsent(lockKey, "1", ttl, TimeUnit.SECONDS);
    }

    public void release() {
        RedisTemplate redisTemplate = holder.get();
        redisTemplate.delete(lockKey);
    }

}
